# encoding=utf8
# from flask_socketio import SocketIO, emit
import paramiko
# import socketio
# socketio = SocketIO()


class SSHProxy(object):
    def __init__(self, hostname, port, username, password):
        self.hostname = hostname
        self.port = port
        self.username = username
        self.password = password
        self.transport = None
        self.event_name = 'dcenter'
        self.name_space = '/dcenter'

    def open(self):
        self.transport = paramiko.Transport((self.hostname, self.port))
        self.transport.connect(username=self.username, password=self.password)

    def command(self, cmd):
        xssh = paramiko.SSHClient()
        xssh._transport = self.transport
        stdin, stdout, stderr = xssh.exec_command(cmd, get_pty=True, timeout=3)
        status = stdout.channel
        stdout = stdout
        code = status.recv_exit_status()
        result = (stdout.read().decode('utf-8'))
        res = {'code': code, 'result': str(result), 'stderr': stderr, 'stdout': stdout}
        return res
        # return result, stderr

    def upload(self, local_path, remote_path):
        sftp = paramiko.SFTPClient.from_transport(self.transport)
        sftp.put(local_path, remote_path)
        sftp.close()

    def close(self):
        self.transport.close()

    def __enter__(self):
        self.open()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


if __name__ == '__main__':
    with SSHProxy('192.168.64.149', 22, 'root', '123456') as ssh:
        ssh.command('pwd')
